<script setup>
import { registerService } from '@/api/user';
import { ElMessage } from 'element-plus';
import { ref, reactive } from 'vue'
import router from '@/router';
import { sendValidation } from '@/api/validation';
import { getAllEthnicService } from '@/api/ethnic'

// const nationalities = [
//     "汉族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族", "满族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族"
// ]

const nationalities = ref([])

async function getAllEthnic() {
    let result = await getAllEthnicService();
    nationalities.value = result.data
}
getAllEthnic()

const form = reactive({
    id: '',
    password: '',
    rePassword: '',
    email: '',
    code: '',
    name: '',
    sex: '',
    age: null,
    ethnic: '',
    img: ''
})

const checkRePsd = (rule, value, cb) => {
    if (value === form.password) {
        return cb();
    }
    //手机号不合法
    cb(new Error('两次输入的密码不同！'));
}

const rules = {
    id: [{ required: true, message: '账号ID不可为空！', trigger: 'blur' }],
    name: [{ required: true, message: '昵称不可为空！', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择您的性别！', trigger: 'blur' }],
    age: [{ required: true, message: '请输入您的年龄', trigger: 'blur' }],
    ethnic: [{ required: true, message: '请选择民族', trigger: 'blur' }],
    email: [
        { required: true, message: '邮箱不可为空！', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    // type: [{ required: true, message: '类型不可为空！', trigger: 'blur' }],
    code: [{ required: true, message: '验证码不可为空！', trigger: 'blur' }],
    password: [{ required: true, message: '密码不可为空！', trigger: 'blur' }],
    rePassword: [
        { required: true, message: '确认密码不可为空！', trigger: 'blur' },
        { validator: checkRePsd, trigger: ['blur', 'change'] }
    ]
}

const isShow = ref(0)

const time = ref(60)
let timer = null

const countdown = () => {
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        if (time.value > 0) {
            time.value--; // 时间减1  
            countdown(); // 递归调用，继续倒计时  
        } else {
            clearTimeout(timer); // 倒计时结束，清除定时器  
            // 在这里可以添加倒计时结束后的处理逻辑  
            isShow.value = 2
            time.value = 60
        }
    }, 1000); // 每秒更新一次时间  
}

const validation = async () => {
    if (form.email === null || form.email === '') {
        ElMessage.error('邮箱不可为空')
    } else {
        await sendValidation(form.email)
        ElMessage.success("验证码发送成功")
        isShow.value = 1
        countdown()
    }
}

const put = async () => {
    await registerService(form)
    ElMessage.success("用户注册成功")
    router.push('/login')
}

const toLogin = () => {
    router.push('/login')
}

// const uploadRef = ref()

// const headers = { Authorization: localStorage.getItem('Authorization') }

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('请上传图片！')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大于2MB!')
        return false
    }
    return true
}

const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const uploadSuccess = (res) => {
    ElMessage.success("上传成功！")
    //   uploadRef.value.clearFiles()
    form.img = res.data
}
const uploadError = () => {
    ElMessage.error("上传失败！")
    //   uploadRef.value.clearFiles()
}

</script>


<template>
    <div
        style="background-image: url('../../public/background.jpg');background-size: cover;width: 100%;height:100vh;overflow: hidden;">
        <div
            style="background-color: rgb(240,248,255,0.85);width: 700px;height: 100%;position: absolute;margin-left: calc(50% - 350px);overflow: hidden;">
            <div style="padding-top: 30px;padding-left: 30px;">
                <span style="color: black;cursor: pointer;font-size: 20px;" @click="toLogin">
                    <el-icon>
                        <DArrowLeft />
                    </el-icon>返回
                </span>
            </div>

            <div style="width: 400px;margin: 0 auto;">
                <div style="color: rgb(143,70,68);font-size: 30px;text-align: center;padding: 30px;">用 户 注 册</div>

                <el-form :model="form" :rules="rules" label-width="80px" >
                    <el-form-item prop="img">
                        <el-upload action="http://localhost:9999/files/uploadFile" :show-file-list="false"
                        :limit="1" :on-remove="handleRemove" class="avatar-uploader"
                        :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeAvatarUpload">
                        <img v-if="form.img" :src="form.img" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                            <spvn style="font-size:10px">点击上传头像</spvn>
                        </el-icon>
                    </el-upload>
                    </el-form-item>
                    <el-form-item prop="id" label="ID">
                        <el-input style="height: 40px;" v-model="form.id" placeholder="输入账号id" clearable />
                    </el-form-item>
                    <el-form-item prop="name" label="昵称">
                        <el-input style="height: 40px;" v-model="form.name" placeholder="输入昵称" clearable />
                    </el-form-item>
                    <el-form-item prop="sex" label="性别">
                        <!-- <el-input style="height: 40px;" v-model="form.sex" placeholder="选择性别" clearable /> -->
                        <el-select v-model="form.sex" placeholder="请选择您的性别" size="large">
                            <el-option label="男" value="男" />
                            <el-option label="女" value="女" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="age" label="年龄">
                        <el-input style="height: 40px;" v-model="form.age" placeholder="输入年龄" type="number" clearable />
                    </el-form-item>
                    <el-form-item prop="ethnic" label="民族">
                        <!-- <el-input style="height: 40px;" v-model="form.ethnic" placeholder="选择您的民族" clearable /> -->
                        <el-select v-model="form.ethnic" placeholder="请选择您的民族" size="large">
                            <el-option v-for="item in nationalities" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="password" label="密码">
                        <el-input style="height: 40px;" v-model="form.password" placeholder="输入密码" clearable />
                    </el-form-item>
                    <el-form-item prop="rePassword" label="确认密码">
                        <el-input style="height: 40px;" v-model="form.rePassword" placeholder="再次输入密码" clearable />
                    </el-form-item>

                    <el-form-item prop="email" label="邮箱">
                        <el-input style="height: 40px;" v-model="form.email" placeholder="输入您的邮箱">
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="code" label="验证码">
                        <el-input style="height: 40px;" v-model="form.code" placeholder="输入邮箱验证码" clearable>

                            <template #suffix>
                                <el-button :type="primary" text style="border: none;color: blue;" v-if="isShow === 0"
                                    @click="validation">获取验证码</el-button>
                                <el-button :type="primary" text style="border: none;color: gray;" v-if="isShow === 1"
                                    disabled>{{ time }}秒</el-button>
                                <el-button :type="primary" text style="border: none;color: blue;" v-if="isShow === 2"
                                    @click="validation">重新获取</el-button>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="put"
                            style="width: 100%;padding: 20px;font-size:20px;margin-top: 20px;">提
                            交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>


<style scoped>
.avatar-uploader .avatar {
  width: 90px;
  height: 90px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #4a4b4d;
  width: 90px;
  height: 90px;
  text-align: center;
}
</style>